package com.hnust.controller.paper.autoPaperController;

import com.hnust.domain.PaperQues;
import com.hnust.domain.QuestionType;
import com.hnust.fx.FXMLController;
import com.hnust.store.AutoPaperDataStore;
import com.hnust.util.NumberJudge;
import com.hnust.view.paper.component.AddAutoPaperKindView;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.*;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextField;
import javafx.stage.StageStyle;
import javafx.util.Callback;
import com.hnust.controller.MainController;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import org.springframework.beans.factory.annotation.Autowired;
import java.io.IOException;
import java.net.URL;
import java.util.*;
import java.util.List;

@FXMLController
public class AutoPaper2Controller implements Initializable {
    @Autowired
    private MainController mainController;
    @Autowired
    private AutoPaperDataStore autoPaperDataStore;
    @Autowired
    private AddAutoPaperKindView addAutoPaperKindView;
    @Autowired
    private NumberJudge numberJudge;
    //大容器
    @FXML
    public ScrollPane container;
    //内包小容器
    @FXML
    public AnchorPane contain;
    @FXML
    public HBox contain_process;
    @FXML
    public HBox line1;
    @FXML
    public HBox line2;
    @FXML
    public HBox line3;
    @FXML
    public ListView<PaperQues> listView;
    private ObservableList<PaperQues> listItem=FXCollections.observableArrayList();
    private Map<String, List<TextField>> textFieldMap=new LinkedHashMap<>();
    private List<PaperQues> paperQuesList=new ArrayList<>();

    public void initialize(URL location, ResourceBundle resources) {
        container.parentProperty().addListener((observable, oldValue, newValue) -> {
            if(newValue!=null){
                if(autoPaperDataStore.getFlag()!=2){
                    clearData();
                }
            }
        });
        container.fitToWidthProperty();
        listenChange();
    }
    //根据窗口改变，进行监听设置页面大小
    public void listenChange(){
    //通过监听最外层容器的宽度，来改变内层Anchor的宽度
    container.widthProperty().addListener(new ChangeListener<Number>() {
        @Override
        public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
            contain.setPrefWidth((double)newValue-2);
        }
    });
    //通过监听最外层容器的高度，来改变内层Anchor的高度
    container.heightProperty().addListener(new ChangeListener<Number>() {
        @Override
        public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
            contain.setPrefHeight((double)newValue-2);
        }
    });
    //设置线条的长度
    contain_process.widthProperty().addListener(new ChangeListener<Number>() {
        @Override
        public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
            line1.setPrefWidth((double)newValue*0.10);
            line2.setPrefWidth((double)newValue*0.10);
            line3.setPrefWidth((double)newValue*0.10);
        }
    });
}
    //回到上一页
    public void before(){
        autoPaperDataStore.setFlag(1);
        mainController.skipView("自动生成试卷");
    }
    //跳转至下一页
    public void toAuto3() throws IOException {
        if(collectData()){
            mainController.skipView("自动生成试卷III");
        }
    }
    //“添加题型按钮的点击事件”
    public void addAutoType() {
        Dialog dialog=new Dialog();
        DialogPane dialogPane=new DialogPane();
        dialogPane.setStyle("-fx-background-color: #FFF;-fx-border-width: 2;-fx-border-color: #ADADAD");
        dialogPane.setContent(addAutoPaperKindView.getView());
        dialog.setDialogPane(dialogPane);
        dialog.setTitle("题型添加");
        dialog.initStyle(StageStyle.UNDECORATED);
        dialog.setGraphic(null);
        ButtonType ok=new ButtonType("确定", ButtonBar.ButtonData.OK_DONE);
        ButtonType cancel=new ButtonType("取消", ButtonBar.ButtonData.CANCEL_CLOSE);
        dialog.getDialogPane().getButtonTypes().addAll(ok,cancel);
        Optional<ButtonType> result=dialog.showAndWait();
        if(result.get()==ok){
            addQuestionKind(autoPaperDataStore.getKind());
        }
    }
    //显示添加题目类型弹窗（选择题、判断题、简答题）
    public void addQuestionKind(String kind){
        addQuestionList(String.valueOf(getQuestionTypeId(kind)), kind);
    }
    //添加选中的题目类型
    public void addQuestionList(String typeId,String type){
        if(!IsExitInList(listItem,typeId)){
            PaperQues paperQues=new PaperQues(typeId,0,0,0,0);
            listItem.add(paperQues);
            showItem();
        }
    }
    //根据题型Id获取题型
    public String getTypeId(String typeId){
        for(QuestionType questionType:autoPaperDataStore.getQuestionTypes()){
            if(typeId.equals(questionType.getId())){
                return questionType.getName();
            }
        }
        return "";
    }
    //展示数据
    public void showItem(){
        listView.setItems(listItem);
        listView.setCellFactory(new Callback<ListView<PaperQues>, ListCell<PaperQues>>() {
            @Override
            public ListCell<PaperQues> call(ListView<PaperQues> param) {
                ListCell<PaperQues> cell=new ListCell<PaperQues>(){
                    @Override
                    protected void updateItem(PaperQues item, boolean empty) {
                        super.updateItem(item, empty);
                        if(empty==false){
                            String typeId=item.getQuestionTypeId();
                            Label label1=new Label("题目类型: " + getTypeId(typeId));
                            label1.setStyle("-fx-text-fill: #000;-fx-font-weight: bold;-fx-font-size: 20;-fx-font-family: 'Adobe 楷体 Std R'");
                            label1.setWrapText(true);
                            VBox vBox0=new VBox(label1);
                            vBox0.setSpacing(5.0);
                            vBox0.setAlignment(Pos.CENTER);
                            vBox0.setPadding(new Insets(25,20,0,0));
                            //输入较易的题目类型个数
                            Label easyLabel=new Label("较易");
                            easyLabel.setStyle("-fx-text-fill: green");
                            TextField easyTextField=new TextField();
                            easyTextField.setPrefWidth(200);
                            VBox vBox1=new VBox(easyLabel,easyTextField);
                            vBox1.setSpacing(5.0);
                            vBox1.setAlignment(Pos.CENTER);
                            //输入中等的题目类型个数
                            Label midLabel=new Label("中等");
                            midLabel.setStyle("-fx-text-fill: blue");
                            TextField midTextField=new TextField();
                            midTextField.setPrefWidth(200);
                            VBox vBox2=new VBox(midLabel,midTextField);
                            vBox2.setSpacing(5.0);
                            vBox2.setAlignment(Pos.CENTER);
                            //输入较难的题目类型个数
                            Label diffLabel=new Label("较难");
                            TextField diffTextField=new TextField();
                            diffTextField.setPrefWidth(200);
                            diffLabel.setStyle("-fx-text-fill: red");
                            VBox vBox3=new VBox(diffLabel,diffTextField);
                            vBox3.setSpacing(5.0);
                            vBox3.setAlignment(Pos.CENTER);
                            //输入分值
                            Label scoreLabel=new Label("分值");
                            TextField scoreTextField=new TextField();
                            scoreTextField.setPrefWidth(200);
                            scoreLabel.setStyle("-fx-text-fill: #000");
                            VBox vBox4=new VBox(scoreLabel,scoreTextField);
                            vBox4.setSpacing(5.0);
                            vBox4.setAlignment(Pos.CENTER);
                            HBox hBox=new HBox(vBox0,vBox1,vBox2,vBox3,vBox4);
                            hBox.setSpacing(10);
                            hBox.setAlignment(Pos.CENTER);
                            List<TextField> list=new ArrayList<>();
                            list.add(easyTextField);
                            list.add(midTextField);
                            list.add(diffTextField);
                            list.add(scoreTextField);
                            textFieldMap.put(typeId, list);
                            this.setGraphic(hBox);
                        }else {
                            this.setGraphic(null);
                        }
                        this.setStyle("-fx-background-color: #FFF");
                    }
                };
                return cell;
            }
        });
        listView.refresh();
    }
    //根据题型，获取题型id
    public String getQuestionTypeId(String typeName){
        for (QuestionType questionType:autoPaperDataStore.getQuestionTypes()){
            if(typeName.equals(questionType.getName())){
                return questionType.getId();
            }
        }
        return "";
    }
    //判断列表中是否有该值
    public Boolean IsExitInList(ObservableList<PaperQues> observableList,String typeId){
        for(PaperQues ques:observableList){
            if(typeId.equals(String.valueOf(ques.getQuestionTypeId()))){
                return true;
            }
        }
        return false;
    }
    //收集所有相关信息并完成打包
    public Boolean collectData(){
        paperQuesList.clear();
        for(Map.Entry<String,List<TextField>> entry:textFieldMap.entrySet()){
            int easyNum=0;
            int midNum=0;
            int diffNum=0;
            int score=0;
            try{
                if(IsNum(entry.getValue().get(0))==1){
                    easyNum=Integer.parseInt(entry.getValue().get(0).getText().trim());
                } else if (IsNum(entry.getValue().get(0))==0){
                    throw new Exception();
                }
                if(IsNum(entry.getValue().get(1))==1){
                    midNum=Integer.parseInt(entry.getValue().get(1).getText().trim());
                }else if (IsNum(entry.getValue().get(1))==0){
                    throw new Exception();
                }
                if(IsNum(entry.getValue().get(2))==1){
                    diffNum=Integer.parseInt(entry.getValue().get(2).getText().trim());
                }else if (IsNum(entry.getValue().get(2))==0){
                    throw new Exception();
                }
                if(IsNum(entry.getValue().get(3))==1){
                    score=Integer.parseInt(entry.getValue().get(3).getText().trim());
                }else if (IsNum(entry.getValue().get(3))==0){
                    throw new Exception();
                }
                PaperQues paperQues=new PaperQues(entry.getKey(),score,easyNum,midNum,diffNum);
                paperQuesList.add(paperQues);
            }catch (Exception e){
                Alert alert=new Alert(Alert.AlertType.ERROR,"请输入数字，不允许输入其他字符！");
                alert.showAndWait();
                paperQuesList.clear();
                return false;
            }
        }
        autoPaperDataStore.setPaperQuesList(paperQuesList);
        return true;
    }
    //判断输入框内容是否数字
    public int IsNum(TextField textField){
        String text=textField.getText();
        if(!"".equals(text.trim())&&numberJudge.isInteger(text)){
            return 1;//不为空且为数字，返回1
        }
        if("".equals(text.trim())){
            return 2;//为空，返回2
        }
        return 0;//不为空且不为数字，返回0
    }
    //清除数据
    public void clearData(){
        paperQuesList.clear();
        textFieldMap.clear();
        listItem.clear();
        listView.getItems().clear();
        listView.refresh();
    }
}
